package com.hzcx.app.simplechat.ui.main;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.google.zxing.BarcodeFormat;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.bean.ChatPushBean;
import com.hzcx.app.simplechat.chat.ChatUtil;
import com.hzcx.app.simplechat.chat.constant.ChatConstant;
import com.hzcx.app.simplechat.chat.util.ChatNoticeUtil;
import com.hzcx.app.simplechat.common.Common;
import com.hzcx.app.simplechat.event.FinishEvent;
import com.hzcx.app.simplechat.event.ImageViewerEvent;
import com.hzcx.app.simplechat.event.TokenErrorEvent;
import com.hzcx.app.simplechat.ui.chat.ChatShareUserActivity;
import com.hzcx.app.simplechat.ui.chat.event.ChatFriendDeleteEvent;
import com.hzcx.app.simplechat.ui.chat.event.ChatListRefreshEvent;
import com.hzcx.app.simplechat.ui.chat.event.ChatShareUserEvent;
import com.hzcx.app.simplechat.ui.chat.event.MainNumChangeEvent;
import com.hzcx.app.simplechat.ui.friend.FriendFragment;
import com.hzcx.app.simplechat.ui.friend.event.AddFriendEvent;
import com.hzcx.app.simplechat.ui.friend.event.AddFriendSuccessEvent;
import com.hzcx.app.simplechat.ui.home.AddFriendActivity;
import com.hzcx.app.simplechat.ui.home.HomeFragment;
import com.hzcx.app.simplechat.ui.home.SloganMenberDialog;
import com.hzcx.app.simplechat.ui.home.dialog.AddFriendDialog;
import com.hzcx.app.simplechat.ui.login.LoginActivity;
import com.hzcx.app.simplechat.ui.login.bean.DomainNameBean;
import com.hzcx.app.simplechat.ui.main.bean.FriendRequestCountBean;
import com.hzcx.app.simplechat.ui.main.contract.MainContract;
import com.hzcx.app.simplechat.ui.main.event.NewFriendRequestEvent;
import com.hzcx.app.simplechat.ui.main.event.NewMomentMsgEvent;
import com.hzcx.app.simplechat.ui.main.event.SendImageMessageEvent;
import com.hzcx.app.simplechat.ui.main.presenter.MainPresenter;
import com.hzcx.app.simplechat.ui.mine.MineFragment;
import com.hzcx.app.simplechat.ui.mine.MineUserInfoActivity;
import com.hzcx.app.simplechat.ui.moment.bean.NewMessageCountBean;
import com.hzcx.app.simplechat.ui.moment.fragment.MomentFragment;
import com.hzcx.app.simplechat.ui.publicui.CaptureResultActivity;
import com.hzcx.app.simplechat.ui.publicui.PublicRoundDialog;
import com.hzcx.app.simplechat.ui.publicui.UpdateVersionDialog;
import com.hzcx.app.simplechat.ui.publicui.WebViewActivity;
import com.hzcx.app.simplechat.ui.publicui.bean.SloganMemberBean;
import com.hzcx.app.simplechat.ui.publicui.bean.UpdateVersionBean;
import com.hzcx.app.simplechat.ui.user.UserInfoActivity;
import com.hzcx.app.simplechat.ui.user.bean.UserInfoBean;
import com.hzcx.app.simplechat.util.TextHttpUtil;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.app.AppHelper;
import com.hzcx.app.simplechat.util.badge.BadgeUtil;
import com.hzcx.app.simplechat.util.down.DownLoadUtil;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.foreground.ForegroundCallbacks;
import com.hzcx.app.simplechat.util.image.ImageUtil;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.map.GdMapUtils;
import com.hzcx.app.simplechat.util.notice.NoticeUtil;
import com.hzcx.app.simplechat.util.qrcode.QRCodeParseUtils;
import com.hzcx.app.simplechat.util.screenshot.ScreenShotListenManager;
import com.hzcx.app.simplechat.util.sp.SPUtils;
import com.hzcx.app.simplechat.util.toast.ToastUtils;
import com.hzcx.app.simplechat.util.token.TokenUtils;
import com.hzcx.app.simplechat.view.autogridview.PhotoLoader;
import com.hzcx.app.simplechat.view.autogridview.PhotoProgressUi;
import com.shuyu.gsyvideoplayer.GSYVideoManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zbar.ZBarView;
import indi.liyi.viewer.ImageViewer;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;


/**
 * 首页-基页
 */
public class MainActivity extends BaseActivity<MainPresenter> implements MainContract.View {

    public static final String INTENT_NOTICE = "INTENT_NOTICE";
    public static final String INTENT_DOWNLOAD_APK = "INTENT_DOWNLOAD_APK";
    public static final String INTENT_DOWNLOAD_STATE = "INTENT_DOWNLOAD_STATE";

    @BindView(R.id.iv_home)
    ImageView ivHome;
    @BindView(R.id.tv_home)
    TextView tvHome;
    @BindView(R.id.cons_home)
    ConstraintLayout consHome;
    @BindView(R.id.iv_friend)
    ImageView ivFriend;
    @BindView(R.id.tv_friend)
    TextView tvFriend;
    @BindView(R.id.cons_friend)
    ConstraintLayout consFriend;
    @BindView(R.id.iv_moment)
    ImageView ivMoment;
    @BindView(R.id.tv_moment)
    TextView tvMoment;
    @BindView(R.id.cons_moment)
    ConstraintLayout consMoment;
    @BindView(R.id.iv_mine)
    ImageView ivMine;
    @BindView(R.id.tv_mine)
    TextView tvMine;
    @BindView(R.id.cons_mine)
    ConstraintLayout consMine;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.frame_layout)
    FrameLayout frameLayout;
    @BindView(R.id.iv_bottom)
    ImageView ivBottom;
    @BindView(R.id.imageViewer)
    ImageViewer imageViewer;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.tv_friend_count)
    TextView tvFriendCount;
    @BindView(R.id.tv_moment_count)
    TextView tvMomentCount;

    private Fragment nowFragment;
    private HomeFragment homeFragment;
    private FriendFragment friendFragment;
    private MomentFragment momentFragment;
    private MineFragment mineFragment;
    private int currentTabIndex = 0;
    private ScreenShotListenManager screenShotListenManager;
    private ImageView saveImageView;
    private int permissionTag = 0;
    private int collectMemberId;
    private String collectImgPath;

    public static MainActivity activity;

    public static MainActivity getInstance() {
        if (activity == null) {
            activity = new MainActivity();
        }
        return activity;
    }

    public Activity getActivity() {
        return activity;
    }

    @Override
    public int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void initPresenter() {
        mPresenter = new MainPresenter();
    }

    @Override
    public void initView() {
        imageViewer.imageLoader(new PhotoLoader());
        setDefaultFragment();
        setBottomImg(0);
    }

    @Override
    public void initData() {

        // 设置环信消息监听
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
        //注册一个监听连接状态的listener
        EMClient.getInstance().addConnectionListener(new MyConnectionListener());

        setMsgNum();

        // 获取好友请求新消息条数
        mPresenter.getFriendRequestCount(this);

        // 获取动态新消息条数
        mPresenter.getMomentCount(this);

        // 创建noteci渠道
        ChatNoticeUtil.getInstance(this).createChannel();
        NoticeUtil.createChannel(this);


        if (getIntent().getBooleanExtra(INTENT_NOTICE, false)) {
            setBottomImg(0);
        }

        LogUtils.d("口令：" + AppHelper.getClipContent());
        // 根据口令获取数据
        if (EmptyUtils.isNotEmpty(AppHelper.getClipContent())) {
            mPresenter.getSloganMenber(this, AppHelper.getClipContent());
        }

        // 监听屏幕截屏
        screenShotListenManager = ScreenShotListenManager.newInstance(this);
        screenShotListenManager.setListener(imagePath -> {
            LogUtils.d("截图路径：" + imagePath);
            mPresenter.upLoadImg(MainActivity.this, imagePath, 1);
        });
        screenShotListenManager.startListen();


        // 申请读写权限
        registerPermission();

        // APP前后台切换监听
        ForegroundCallbacks.init(getApplication()).addListener(new ForegroundCallbacks.Listener() {
            @Override
            public void onBecameForeground() {
                LogUtils.d("应用进入前台");
                mPresenter.putAppOnlineRecord(MainActivity.this);
            }

            @Override
            public void onBecameBackground() {
                LogUtils.d("应用进入后台");
            }
        });

        // 通知服务器自己在线
        mPresenter.putServiceOnline(this);

        // 获取域名配置
        mPresenter.getDomainNameConfig(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }


    @OnClick({R.id.cons_home, R.id.cons_friend, R.id.cons_moment, R.id.cons_mine})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.cons_home:  // 首页
                setBottomImg(0);
                break;

            case R.id.cons_friend: // 通讯录
                setBottomImg(1);
                break;

            case R.id.cons_moment: // 动态
                setBottomImg(2);
                break;

            case R.id.cons_mine: // 我的
                setBottomImg(3);
                break;
        }
    }

    /**
     * 设置默认fragment
     */
    private void setDefaultFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        homeFragment = new HomeFragment();
        mineFragment = new MineFragment();
        transaction.add(R.id.frame_layout, mineFragment).hide(mineFragment);
        transaction.add(R.id.frame_layout, homeFragment);
        nowFragment = homeFragment;
        transaction.commit();
    }

    /**
     * 设置底部菜单展示
     *
     * @param index
     */
    private void setBottomImg(int index) {
        currentTabIndex = index;
        ivHome.setImageResource(R.mipmap.ic_icon_tab_home_normal);
        ivFriend.setImageResource(R.mipmap.ic_icon_tab_friend_normal);
        ivMoment.setImageResource(R.mipmap.ic_icon_tab_moment_normal);
        ivMine.setImageResource(R.mipmap.ic_icon_tab_mine_normal);

        tvHome.setTextColor(getResources().getColor(R.color.color_282F3E));
        tvFriend.setTextColor(getResources().getColor(R.color.color_282F3E));
        tvMoment.setTextColor(getResources().getColor(R.color.color_282F3E));
        tvMine.setTextColor(getResources().getColor(R.color.color_282F3E));
        switch (index) {
            case 0:
                ivHome.setImageResource(R.mipmap.ic_icon_tab_home_selete);
                tvHome.setTextColor(getResources().getColor(R.color.color_2D7CFD));
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                }
                switchContent(homeFragment);
                break;
            case 1:
                ivFriend.setImageResource(R.mipmap.ic_icon_tab_friend_selete);
                tvFriend.setTextColor(getResources().getColor(R.color.color_2D7CFD));
                if (friendFragment == null) {
                    friendFragment = new FriendFragment();
                }
                switchContent(friendFragment);
                tvFriendCount.setVisibility(View.GONE);
                break;
            case 2:
                ivMoment.setImageResource(R.mipmap.ic_icon_tab_moment_selete);
                tvMoment.setTextColor(getResources().getColor(R.color.color_2D7CFD));
                if (momentFragment == null) {
                    momentFragment = new MomentFragment();
                }
                switchContent(momentFragment);
                tvMomentCount.setVisibility(View.GONE);
                break;
            case 3:
                ivMine.setImageResource(R.mipmap.ic_icon_tab_mine_selete);
                tvMine.setTextColor(getResources().getColor(R.color.color_2D7CFD));
                if (mineFragment == null) {
                    mineFragment = new MineFragment();
                }
                switchContent(mineFragment);
                break;
        }
    }

    /**
     * 切换fragment
     *
     * @param ToFragment
     */
    public void switchContent(Fragment ToFragment) {
        if (nowFragment != ToFragment) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (!ToFragment.isAdded()) { // 先判断是否被add过
                transaction.hide(nowFragment).add(R.id.frame_layout, ToFragment).commit(); // 隐藏当前的fragment
            } else {
                transaction.hide(nowFragment).show(ToFragment).commit(); // 隐藏当前的fragment，显示下一个
            }
            nowFragment = ToFragment;
        }
    }

    /**
     * 展示列表大图
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showImgs(ImageViewerEvent event) {
        collectMemberId = event.getId();
        imageViewer.overlayStatusBar(true)
                .imageData(event.getImgs())
                .bindViewGroup(event.getViewGroup())
                .loadProgressUI(new PhotoProgressUi())
                .setOnItemLongPressListener((position, imageView) -> {
                    saveImgToPhoto(imageView, event.getImgs().get(position));
                    return false;
                })
                .watch(event.getPostion());
    }

    /**
     * 申请文件读写权限
     */
    private void registerPermission() {
        PermissionGen.with(this)
                .addRequestCode(Common.BASIC_PERMISSION_REQUEST_CODE)
                .permissions(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.READ_PHONE_STATE)
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    /**
     * 权限申请失败
     */
    @PermissionFail(requestCode = Common.BASIC_PERMISSION_REQUEST_CODE)
    public void openFail() {
        ToastUtils.show("权限获取失败，无法保存图片");
    }

    /**
     * 权限申请成功
     */
    @PermissionSuccess(requestCode = Common.BASIC_PERMISSION_REQUEST_CODE)
    public void openSuccess() {
        if (permissionTag == 0) {
            mPresenter.updateVersion(this);
            GdMapUtils.getInstance().startLocation(aMapLocation -> {
                if (aMapLocation.getErrorCode() != 0) {
                    LogUtils.d("定位失败");
                    return;
                }
                LogUtils.d("定位地址：" + aMapLocation.getAddress());
                mPresenter.putUserLocation(MainActivity.this, aMapLocation.getLatitude(), aMapLocation.getLongitude(), aMapLocation.getAddress());
            });
        } else {
            ImageUtil.saveMyBitmap(this, ((BitmapDrawable) saveImageView.getDrawable()).getBitmap(), "chat_" + System.currentTimeMillis() + ".jpg");
        }
    }

    /**
     * 保存图片到相册
     */
    private void saveImgToPhoto(ImageView imageView, String url) {
        saveImageView = imageView;
        new Thread(() -> {
            Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
            String result = QRCodeParseUtils.syncDecodeQRCode(bitmap);
            Message msg = new Message();
            msg.what = 0x03;
            Bundle bundle = new Bundle();
            bundle.putString("url", url);
            bundle.putString("qrcode", result);
            msg.obj = result;
            msg.setData(bundle);
            handler.sendMessage(msg);
        }).start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x01) {
                mPresenter.putServiceOnline(MainActivity.this);
            } else if (msg.what == 0x02) {
                String result = msg.obj == null ? null : (String) msg.obj;
                LogUtils.d(result);
                if (EmptyUtils.isEmpty(result)) {
                    showError("未识别到二维码信息");
                    return;
                }
                if (result.contains("chat_number")) {
                    // 如果是多聊二维码，调用接口
                    mPresenter.getUserInfoByQrCode(MainActivity.this, result);
                } else if (TextHttpUtil.hasNetUrlHead(result)) {
                    // 网页链接，跳转到web界面
                    startActivity(new Intent(MainActivity.this, WebViewActivity.class)
                            .putExtra(WebViewActivity.INTENT_WEB_URL, result));
                } else {
                    // 都不是，直接展示结果
                    startActivity(new Intent(MainActivity.this, CaptureResultActivity.class)
                            .putExtra(CaptureResultActivity.INTENT_RESULT, result));
                }
            } else if (msg.what == 0x03) {
                Bundle bundle = msg.getData();
                String qrcode = bundle.getString("qrcode");
                List<String> list = new ArrayList<>();
                list.add("发送给朋友");
                list.add("收藏");
                list.add("保存到相册");
                if (EmptyUtils.isNotEmpty(qrcode)) {
                    list.add("识别图中二维码");
                }
                PublicRoundDialog roundDialog = new PublicRoundDialog(MainActivity.this, list, (pos, menu) -> {
                    switch (menu) {
                        case "发送给朋友":
                            collectImgPath = bundle.getString("url");
                            startActivity(new Intent(MainActivity.this, ChatShareUserActivity.class)
                                    .putExtra(ChatShareUserActivity.INTENT_FROM_TAG, 6));
                            break;

                        case "收藏":
                            collectImg(bundle.getString("url"));
                            break;
                        case "保存到相册":
                            permissionTag = 1;
                            registerPermission();
                            break;
                        case "识别图中二维码":
//                            new Thread(() -> {
//                                Bitmap bitmap = ((BitmapDrawable) saveImageView.getDrawable()).getBitmap();
//                                String result = QRCodeParseUtils.syncDecodeQRCode(bitmap);
//                                Message message = new Message();
//                                message.what = 0x02;
//                                message.obj = result;
//                                handler.sendMessage(message);
//                            }).start();
                            if (EmptyUtils.isEmpty(qrcode)) {
                                showError("未识别到二维码信息");
                                return;
                            }
                            if (qrcode.contains("chat_number")) {
                                // 如果是多聊二维码，调用接口
                                mPresenter.getUserInfoByQrCode(MainActivity.this, qrcode);
                            } else if (TextHttpUtil.hasNetUrlHead(qrcode)) {
                                // 网页链接，跳转到web界面
                                startActivity(new Intent(MainActivity.this, WebViewActivity.class)
                                        .putExtra(WebViewActivity.INTENT_WEB_URL, qrcode));
                            } else {
                                // 都不是，直接展示结果
                                startActivity(new Intent(MainActivity.this, CaptureResultActivity.class)
                                        .putExtra(CaptureResultActivity.INTENT_RESULT, qrcode));
                            }
                            break;
                    }
                });
                roundDialog.show();
            }
        }
    };

    /**
     * 收藏图片
     */
    private void collectImg(String url) {
        DownLoadUtil.downLoadImg(url, new DownLoadUtil.OnDownLoadListener() {
            @Override
            public void success(String path) {
                mPresenter.upLoadImg(MainActivity.this, path, 2);
            }

            @Override
            public void fail() {
                showError("图片下载失败");
            }
        });
    }


    /**
     * 环信消息监听
     */
    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {

            for (EMMessage msg : messages) {
                // 声音及震动通知
                ChatNoticeUtil.getInstance(MainActivity.this).vibrateAndPlayTone(msg);
            }

            refreshUIWithMessage();
            setMsgNum();
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            for (EMMessage msg : messages) {
                try {
                    EMCmdMessageBody body = (EMCmdMessageBody) msg.getBody();
                    LogUtils.d("透传body:" + body.action());
                    pushByCode(body.action());

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            refreshUIWithMessage();
            setMsgNum();
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
            LogUtils.d("收到已读回执消息");
            if (homeFragment != null) {
                homeFragment.refresh();
            }
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
        }

        @Override
        public void onMessageRecalled(List<EMMessage> messages) {
            refreshUIWithMessage();
            setMsgNum();
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
        }
    };

    /**
     * 刷新消息列表
     */
    private void refreshUIWithMessage() {
        runOnUiThread(() -> {
            // refresh conversation list
            if (homeFragment != null) {
                homeFragment.refresh();
            }
        });
    }

    /**
     * 根据透传的code刷新UI
     *
     * @param body
     */
    private void pushByCode(String body) {
        ChatPushBean bean = new Gson().fromJson(body, ChatPushBean.class);
        long nowTime = System.currentTimeMillis() / 1000;
        if (nowTime - bean.getTimestamp() > (60)) {
            LogUtils.d(TAG, "时间戳过期");
            return;
        }
        switch (bean.getCode()) {
            case 201: // 动态新消息
                mPresenter.getMomentCount(this);
                break;

            case 202: // 新的好友请求
                mPresenter.getFriendRequestCount(this);
                break;

            case 203: // 对方同意好友请求
                EventBus.getDefault().post(new AddFriendEvent(bean.getMember_id()));
                break;

            case 207: // 对方删除好友
                EventBus.getDefault().post(new ChatFriendDeleteEvent(bean.getMember_id()));
                break;

            case 208: // 会员状态改变
                UserInfoUtil.updateUserVip(bean.getIs_plus());
                EventBus.getDefault().post(new AddFriendSuccessEvent());
                EventBus.getDefault().post(new ChatListRefreshEvent());
                break;
        }
    }

    /**
     * 获取好友请求新消息条数成功
     *
     * @param data
     */
    @Override
    public void friendRequestCountResult(FriendRequestCountBean data) {
        if (data.getBuddy_count() <= 0) {
            return;
        }
        if (nowFragment != friendFragment) {
            tvFriendCount.setText(data.getBuddy_count() + "");
            tvFriendCount.setVisibility(View.VISIBLE);
        }
        EventBus.getDefault().post(new NewFriendRequestEvent(data.getBuddy_count()));
    }

    /**
     * 动态新消息条数获取成功
     *
     * @param data
     */
    @Override
    public void momentCountResult(NewMessageCountBean data) {
        if (data.getNews_count() <= 0) {
            return;
        }
        if (nowFragment != momentFragment) {
            tvMomentCount.setVisibility(View.VISIBLE);
        }
        EventBus.getDefault().post(new NewMomentMsgEvent(data.getNews_count()));
    }

    /**
     * 口令数据获取成功
     *
     * @param data
     */
    @Override
    public void sloganMemberResult(SloganMemberBean data) {
        if (data.getIs_buddy() == 1) {
            if (data.getIs_del() == 1) {
//                startActivity(new Intent(this, AddFriendActivity.class)
//                        .putExtra(AddFriendActivity.INTENT_USER_ID, data.getMember_id())
//                        .putExtra(AddFriendActivity.INTENT_TYPE, 3));
                mPresenter.getUserInfo(this, data.getMember_id(), false);
            } else {
                startActivity(new Intent(this, UserInfoActivity.class)
                        .putExtra(UserInfoActivity.INTENT_USER_ID, data.getMember_id()));
            }
        } else {
//            startActivity(new Intent(this, AddFriendActivity.class)
//                    .putExtra(AddFriendActivity.INTENT_USER_ID, data.getMember_id())
//                    .putExtra(AddFriendActivity.INTENT_TYPE, 3));
            mPresenter.getUserInfo(this, data.getMember_id(), false);
        }
    }

    /**
     * 图片上传成功
     *
     * @param url
     */
    @Override
    public void upLoadSucces(String url, int tag) {
        if (tag == 1) {
            mPresenter.riskRecordImg(this, url);
        } else {
            // 收藏图片
            mPresenter.addChatCollect(this, null, url, collectMemberId);
        }
    }

    /**
     * 截图图片上传成功
     */
    @Override
    public void riskRecordImgSuccess() {
        LogUtils.d("截图上传成功");
    }

    /**
     * 版本更新内容获取成功
     *
     * @param data
     */
    @Override
    public void updateVersionResult(UpdateVersionBean data) {
        try {
            if (data == null || EmptyUtils.isEmpty(data.getDownload_link())) {
                return;
            }
//            UpdateVersionDialog versionDialog = new UpdateVersionDialog(this, data, new UpdateVersionDialog.OnUpdateVersionListener() {
////                @Override
////                public void update(String url) {
////                    DownLoadUtil.downLoadNewVersion(MainActivity.this, url);
////                }
////            });
////            versionDialog.show();

            if (isFinishing()){
                return;
            }
            UpdateVersionDialog versionDialog = new UpdateVersionDialog(this, data, url -> {
//                startActivity(new Intent(MainActivity.this, WebViewActivity.class)
//                        .putExtra(WebViewActivity.INTENT_WEB_URL, url));

                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            });
            versionDialog.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 收藏成功
     */
    @Override
    public void collectSuccess() {
        showError("收藏成功");
    }

    /**
     * 应用到前台-通知服务端
     */
    @Override
    public void putOnlineSuccess() {
        LogUtils.d("通知服务端成功");
    }

    /**
     * 通知服务器自己在线成功
     */
    @Override
    public void putServiceOnlineSuccess() {
        LogUtils.d("通知服务器自己在线成功");
        if (handler != null) {
            if (handler.hasMessages(0x01)) {
                handler.removeMessages(0x01);
            }
            handler.sendEmptyMessageDelayed(0x01, 1000 * 60 * 5);
        }
    }

    /**
     * 根据二维码获取用户信息成功
     *
     * @param data
     */
    @Override
    public void userInfoResult(UserInfoBean data) {
        if (data.getMember_id() == UserInfoUtil.getUserId()) {
            startActivity(new Intent(this, MineUserInfoActivity.class));
            return;
        }
        if (data.getIs_buddy() == 1) {
            startActivity(new Intent(this, UserInfoActivity.class)
                    .putExtra(UserInfoActivity.INTENT_USER_ID, data.getMember_id()));
        } else {
            startActivity(new Intent(this, AddFriendActivity.class)
                    .putExtra(AddFriendActivity.INTENT_USER_ID, data.getMember_id())
                    .putExtra(AddFriendActivity.INTENT_TYPE, 2));
        }
    }

    /**
     * 根据二维码获取用户信息失败
     */
    @Override
    public void onFail() {

    }

    /**
     * 用户地址上传成功
     */
    @Override
    public void addressPutSuccess() {
        LogUtils.d("地址上传成功");
    }

    /**
     * 根据ID获取用户信息成功
     *
     * @param data
     */
    @Override
    public void userInfoResultById(UserInfoBean data) {
        SloganMenberDialog sloganMenberDialog = new SloganMenberDialog(this, data, (id, remark) ->
                showAddFriendDialog(id));
        sloganMenberDialog.show();
    }

    /**
     * 添加好友请求发送成功
     */
    @Override
    public void sendAddFriendSuccess() {
        showError("好友请求发送成功");
    }

    /**
     * 添加好友弹窗
     *
     * @param id
     */
    private void showAddFriendDialog(int id) {
        AddFriendDialog addFriendDialog = new AddFriendDialog(this, remark -> mPresenter.sendAddFriendRequest(MainActivity.this, id, remark
                , 3));
        addFriendDialog.show();
    }

    /**
     * 环信连接状态监听
     */
    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
            LogUtils.d("连接成功");
        }

        @Override
        public void onDisconnected(int error) {
            LogUtils.d("连接失败：" + error);
            if (error == EMError.USER_REMOVED) {
                kickout();
            } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                kickout();
            }
        }
    }


    /**
     * 踢出
     */
    private void kickout() {
        new Thread(() -> {
            EventBus.getDefault().post(new FinishEvent());
            startActivity(new Intent(MainActivity.this, LoginActivity.class)
                    .putExtra(LoginActivity.INTENT_TAG_KICKOUT, true));
            TokenUtils.logout(MainActivity.this);
        }).start();
    }

    /**
     * 设置消息数量
     */
    private void setMsgNum() {
        runOnUiThread(() -> {
            int num = EMClient.getInstance().chatManager().getUnreadMessageCount();
            if (num > 0) {
                tvNum.setText(num + "");
                tvNum.setVisibility(View.VISIBLE);
                BadgeUtil.setBadgeCount(this, num, R.mipmap.ic_launcher);
            } else {
                tvNum.setVisibility(View.GONE);
            }
        });

    }

    /**
     * 新消息数量有变化
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void numChange(MainNumChangeEvent event) {
        setMsgNum();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        setMsgNum();

    }

    /**
     * token错误或过期
     *
     * @param errorEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void tokenError(TokenErrorEvent errorEvent) {
        showError("登录状态已失效，请重新登录");
        new Thread(() -> {
            EventBus.getDefault().post(new FinishEvent());
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
            TokenUtils.logout(MainActivity.this);
        }).start();
    }

    /**
     * 监听返回键
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean b = imageViewer.onKeyDown(keyCode, event);
        if (b) {
            return b;
        } else {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                AppHelper.backFinish();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 转发选择好友返回
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void selectUserResult(ChatShareUserEvent event) {
        if (event.getTag() == 6) {
            showLoading();
            DownLoadUtil.downLoadImg(collectImgPath, new DownLoadUtil.OnDownLoadListener() {
                @Override
                public void success(String path) {
                    hideLoading();
                    ChatUtil.getInstance().sendImgMessage(MainActivity.this, path, event.getBean().getHxusername(), ChatConstant.CHATTYPE_SINGLE,
                            event.getBean().getMember_id(), EmptyUtils.isEmpty(event.getBean().getRemarks_name()) ? event.getBean().getNickname() :
                                    event.getBean().getRemarks_name(), null);
                    showError("发送成功");
                }

                @Override
                public void fail() {
                    hideLoading();
                    showError("图片下载失败");
                }
            });
        }
    }

    /**
     * 发送图片消息
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void sendChatImgMessage(SendImageMessageEvent event) {
        ChatUtil.getInstance().sendImgMessage(this, event.getPath(), event.getUsername(), event.getChatType(), event.getReceiveId(),
                event.getNickName(),
                event.getCallback());
    }

    @Override
    public void onBackPressed() {
        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }

    @Override
    protected void onResume() {
        try {
            super.onResume();
        }catch (Exception e){
            e.printStackTrace();
        }
        GSYVideoManager.onResume();
        LogUtils.d("下载状态：" + getIntent().getIntExtra(INTENT_DOWNLOAD_STATE, 0));
        // 如果是下载notice点击过来的
        if (getIntent().getBooleanExtra(INTENT_DOWNLOAD_APK, false)) {
            if (getIntent().getIntExtra(INTENT_DOWNLOAD_STATE, 0) == -1) {
                // 下载失败
                permissionTag = 0;
                registerPermission();
            } else if (getIntent().getIntExtra(INTENT_DOWNLOAD_STATE, 0) == 2) {
                // 下载成功
                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/duoChat.apk";
                File file = new File(path);
                if (file.exists()) {
                    AppHelper.installApk(this, path);
                }
            }
        }

        LogUtils.d("口令：" + AppHelper.getClipContent());
        // 根据口令获取数据
        if (EmptyUtils.isNotEmpty(AppHelper.getClipContent())) {
            mPresenter.getSloganMenber(this, AppHelper.getClipContent());
        }
    }

    /**
     * 域名配置获取成功
     *
     * @param data
     */
    @Override
    public void domainNameResult(DomainNameBean data) {
        SPUtils.put(this, Common.DOMAIN_NAME_URL, data.getDomain_url());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
    }
}
